<?php
/**
 * @package		站群管理系统·子站管理模块
 * @subpackage	文章频道管理函数包
 * @version		$Id: function_portalcp.php 23 2012-06-11 18:04:03Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2009 Hoping Software Studio. All rights reserved.
 */


/**
 * 获取正文中的图片列表
 *
 * @param 数组 $attach 附件列表
 * @return 附件聊表HTML代码
 */
function get_uploadcontent($attach) {

	$return = '';
	if($attach['isimage']) {
		$pic = pic_get($attach['attachment'], 'portal', $attach['thumb'], $attach['remote'], 0);
		$small_pic = $attach['thumb'] ? ($pic.'.thumb.jpg') : '';
		$check = $attach['pic'] == $attach['attachment'] ? checked : '';
		$aid = $check ? $attach['aid'] : '';

		$return .= '<table id="attach_list_'.$attach['attachid'].'" width="100%" class="xi2">';
		$return .= '<td width="50" class="bbs"><a href="'.$pic.'" target="_blank"><img src="'.($small_pic ? $small_pic : $pic).'" width="40" height="40"></a></td>';
		$return .= '<td class="bbs">';
		$return .= '<label for="setconver'.$attach['attachid'].'"><input type="radio" name="setconver" id="setconver'.$attach['attachid'].'" class="pr" value="1" onclick=setConver(\''.addslashes(serialize(array('pic'=>$attach['attachment'], 'thumb'=>$attach['thumb'], 'remote'=>$attach['remote']))).'\') '.$check.'> '.lang('portalcp', 'Set to conver').'</label><br>';
		if($small_pic) $return .= '<a href="javascript:void(0);" onclick="insertImage(\''.$small_pic.'\', \''.$pic.'\');return false;">'.lang('portalcp', 'Insert small image').'</a><br>';
		$return .= '<a href="javascript:void(0);" onclick="insertImage(\''.$pic.'\');return false;">'.lang('portalcp', 'Insert large image').'</a><br>';
		$return .= '<a href="javascript:void(0);" onclick="deleteAttach(\''.$attach['attachid'].'\', \'index.php?task=attachment&id='.$attach['attachid'].'&aid='.$aid.'&op=delete\');return false;">'.lang('portalcp', 'Delete').'</a>';
		$return .= '</td>';
		$return .= '</table>';

	} else {
		$return .= '<table id="attach_list_'.$attach['attachid'].'" width="100%">';
		$return .= '<td><a href="index.php?task=attachment&id='.$attach['attachid'].'" target="_blank">'.$attach['filename'].'</a></td>';
		$return .= '<td>';
		$return .= '<a href="javascript:void(0);" onclick="insertFile(\''.$attach['filename'].'\', \'index.php?task=attachment&id='.$attach['attachid'].'\');return false;">'.lang('portalcp', 'Insert file').'</a><br>';
		$return .= '<a href="javascript:void(0);" onclick="deleteAttach(\''.$attach['attachid'].'\', \'index.php?task=attachment&id='.$attach['attachid'].'&op=delete\');return false;">'.lang('portalcp', 'Delete').'</a>';
		$return .= '</td>';
		$return .= '</table>';
	}
	return $return;
}

function checkprimaltpl($template) {
	global $_G;

	$primaltplname = ROOT_PATH.$_G['cache']['style_default']['tpldir'].'/'.$template.'.htm';
	if (!file_exists($primaltplname)) {
		$primaltplname = ROOT_PATH.'./template/default/'.$template.'.htm';
	}
	if (!is_file($primaltplname)) showmessage('diy_template_noexist');
	return $primaltplname;
}

function category_showselect($type, $name='catid', $shownull=true, $current='') {
	global $_G;
	if(! in_array($type, array('portal', 'blog', 'album'))) {
		return '';
	}
	loadcache($type.'category');
	$category = $_G['cache'][$type.'category'];

	$select = "<select id=\"$name\" name=\"$name\" class=\"ps vm\">";
	if($shownull) {
		$select .= '<option value="">'.lang('portalcp', 'Select category').'</option>';
	}
	foreach ($category as $value) {
		if($value['level'] == 0) {
			$selected = ($current && $current==$value['catid']) ? 'selected="selected"' : '';
			$select .= "<option value=\"$value[catid]\"$selected>$value[catname]</option>";
			if(!$value['children']) {
				continue;
			}
			foreach ($value['children'] as $catid) {
				$selected = ($current && $current==$catid) ? 'selected="selected"' : '';
				$select .= "<option value=\"{$category[$catid][catid]}\"$selected>-- {$category[$catid][catname]}</option>";
				if($category[$catid]['children']) {
					foreach ($category[$catid]['children'] as $catid2) {
						$selected = ($current && $current==$catid2) ? 'selected="selected"' : '';
						$select .= "<option value=\"{$category[$catid2][catid]}\"$selected>---- {$category[$catid2][catname]}</option>";
					}
				}
			}
		}
	}
	$select .= "</select>";
	return $select;
}

function category_get_childids($type, $catid, $depth=3) {
	global $_G;
	if(! in_array($type, array('portal', 'blog', 'album'))) {
		return array();
	}
	loadcache($type.'category');
	$category = $_G['cache'][$type.'category'];
	$catids = array();
	if(isset($category[$catid]) && !empty($category[$catid]['children']) && $depth) {
		$catids = $category[$catid]['children'];
		foreach((array)$category[$catid]['children'] as $id) {
			$catids = array_merge($catids, category_get_childids($type, $id, $depth-1));
		}
	}
	return $catids;
}

function category_get_num($type, $catid) {
	global $_G;
	if(! in_array($type, array('portal', 'blog', 'album'))) {
		return array();
	}
	loadcache($type.'category');
	$category = $_G['cache'][$type.'category'];

	$numkey = $type == 'portal' ? 'articles' : 'num';
	if(! isset($_G[$type.'category_nums'])) {
		$_G[$type.'category_nums'] = array();
		$query = DB::query("SELECT catid, $numkey FROM #__common_category");
		while($value=DB::fetch($query)) {
			$_G[$type.'category_nums'][$value['catid']] = intval($value[$numkey]);
		}
	}

	$nums = $_G[$type.'category_nums'];
	$num = intval($nums[$catid]);
	if($category[$catid]['children']) {
		foreach((array)$category[$catid]['children'] as $id) {
			$num += category_get_num($type, $id);
		}
	}
	return $num;
}

/**
 * 转换中文为英文
 *
 * @param mixed $str
 * @return mixed
 */
function translate($str, $fromLang, $toLang) {
	global $cmsLang;
	if(!$fromLang) $fromLang = $cmsLang->_userLang;
	if(!$toLang) $toLang = 'en';
	if($fromLang == $toLang) return $str;
	if (! empty ( $str )) {
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode ( $str ) . '&langpair='.$fromLang.'%7C'.$toLang );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		$result = curl_exec ( $ch );
		curl_close ( $ch );
		return ecm_json_decode ( $result )->responseData->translatedText;
	} else {
		return $str;
	}
}

function ecm_json_decode($value, $type = 0) {
	if (CHARSET == 'utf-8' && function_exists('json_decode')) {
		return empty($type) ? json_decode($value) : get_object_vars_deep(json_decode($value));
	}
	if (!class_exists('JSON')) {
		require_once libfile('class/json');
	}
	$json = new JSON();
	return $json->decode($value, $type);
}
/**
 * 返回由对象属性组成的关联数组
 *
 * @access   pubilc
 * @param    obj    $obj
 *
 * @return   array
 */
function get_object_vars_deep($obj) {
	if (is_object($obj)) {
		$obj = get_object_vars($obj);
	}
	if (is_array($obj)) {
		foreach ($obj as $key => $value) {
			$obj[$key] = get_object_vars_deep($value);
		}
	}
	return $obj;
}
function getTranslate($str, $fromLang, $toLang) {
	if(strlen($str)>200) {
		$result = splithtml($str);
		$str = '';
		foreach((array)$result as $var) {
			//已经分隔了HTML控制符，所以，当第一个字符是<的话，就忽略本句的翻译！
			if(substr($var,0,1)!='<') {
				$t = translate($var, $fromLang, $toLang);
				if($t) {
					$str .= $t;
				} else {
					$str .= $var;
				}
			} else {
				$str .= $var;
			}
		}
		$str = str_replace(' <ssss> ', '', $str);
	} else {
		$str = translate($str, $fromLang, $toLang);
	}
	return $str;
}

function splithtml($str) {
	$split = array();
	if(substr($str, 0, 1)!='<') $str = ' <ssss> '.$str;
	if(substr($str, -1)!='>') $str = $str.' <ssss> ';
	$uin = md5(time());
	$str = str_replace('><', $uin, $str);
	$str = preg_replace('/[\r|\n]*/', '', $str);
	$str = preg_replace('/>[\r|\n|\s|\t]*</', $uin, $str);
	$result = preg_match_all('@(<[^>]+>)([^<]+)@i', $str, $match);
	if($result) {
		$str = '';
		foreach((array)$match[2] as $key=>$var) {
			$split[] = $match[1][$key];
			if(strlen($var)>200) {
				$var = splitpunctuation($var);
				$split = array_merge($split, $var);
			} else {
				$split[] = $var;
			}
		}
	}
	if($split){
		foreach((array)$split as $k=>$v){
			$v = str_replace($uin, '><', trim($v));
			$split[$k] = $v;
		}
	}
	return $split;
}
function splitpunctuation($str) {
	$str = str_replace(array('，','。','？','！'), array(', ', '. ', '? ', '! '), $str);
	$split = array();
	$regex = '/([^,|^\.|^\?|^\!]+)([,|\.|\!|\?]+)/';
	$result = preg_match_all($regex, $str, $match);
	if($result) {
		foreach((array)$match[0] as $k=>$var) {
			$ss = $var.$match[2][$k];
			$split[] = $var;
		}
		$str = array();
		$tmp = '';
		foreach((array)$split as $k=>$v){
			if(strlen($tmp.$v)<200){
				$tmp.=$v;
			} elseif(!$tmp) {
				$str[] = $v;
			} else {
				$str[] = $tmp;
				$tmp = '';
			}
		}
		if($tmp) $str[] = $tmp;
		return $str;
	}
	return array($str);
}


function getcattree(){
	require_once libfile('function/portalcp');
	$category = getglobal('cache/portalcategory');
	require_once libfile('class/tree');
	$tree = new tree();
	foreach((array)$category as $key=>$value){
		$tree->setNode($value['catid'], $value['upid'], $value);
	}

	$cattree = array();
	foreach ($category as $k=>$v) {
		if(!isset($cattree[$v['catid']])) $cattree[$v['catid']] = $v;
		$values = $tree->getChilds($v['catid']);
		foreach ($values as $key => $id) {
			$one = $tree->getValue($id);
			$one['catname'] = str_repeat('&nbsp;', $tree->getLayer($id) * 4). $one['catname'];
			$cattree[$id] = $one;
			unset($category[$id]);
		}
	}
	return $cattree;
}

function portalcp_get_summary($message) {
	$message = preg_replace(array("/\[attach\].*?\[\/attach\]/", "/\&[a-z]+\;/i", "/\<script.*?\<\/script\>/"), '', $message);
	$message = preg_replace("/\[.*?\]/", '', $message);
	$message = getstr(strip_tags($message), 200);
	return $message;
}


function showcategoryrow($key, $level = 0, $last = '') {
	global $category, $permissioncategory, $permission;

	$value = $category[$key];
	$return = '';

	$op = '';
	$value['articles'] = category_get_num('portal', $key);
	if (checkperm('allowmanagearticle') || checkperm('allowmanage') || $permission[$key]['allowmanage']) {
		$op .= '<a href="index.php?option=portalcp&task=category&catid='.$key.'" class="y">'.lang('portalcp', 'Article manage').'</a>';
	}
	if ((checkperm('allowmanagearticle') || checkperm('allpublish') || $permission[$key]['allowpublish']) && empty($value['disallowpublish'])) {
		if($op) $op .= '<span class="pipe y">|</span>';
		$op .= '<a href="index.php?option=portalcp&task=article&catid='.$value['catid'].'" target="_blank" class="y">'.lang('portalcp', 'Article publish').'</a>';
	}

	if($level == 2) {
		$class = $last ? 'lastchildcat' : 'childcat';
		$return = '<tr class="hover"><td><div class="'.$class.'"><a href="index.php?option=portalcp&task=category&catid='.$key.'">'.$value['catname'].'</a>'.
		'</div></td><td>'.$value['articles'].'</td><td>'.$op.'</td></tr>';
	} elseif($level == 1) {
		$return = '<tr class="hover"><td><div class="cat"><a href="index.php?option=portalcp&task=category&catid='.$key.'">'.$value['catname'].'</a>'.
		'</td><td>'.$value['articles'].'</td><td>'.$op.'</td></tr>';
		$children = checkperm('allowmanagearticle') ? $category[$key]['children'] : $permissioncategory[$key]['permissionchildren'];
		$i = 1;
		$l = count($children);
		if($children)
		foreach((array)$children as $v){
			$return .= showcategoryrow($v, 2 ,$i++ == $l);
		}
	} else {
		$return = '<tr class="hover"><td><div class="parentcat"><a href="index.php?option=portalcp&task=category&catid='.$key.'">'.$value['catname'].'</a>'.
		'</div></td><td>'.$value['articles'].'</td><td>'.$op.'</td></tr>';
		$children = checkperm('allowmanagearticle') ? $category[$key]['children'] : $permissioncategory[$key]['permissionchildren'];
		if($children)
		foreach((array)$children as $v){
			$return .= showcategoryrow($v, 1);
		}
	}
	return $return;
}

function showcategoryrowpush($key, $level = 0, $last = '') {
	global $_G, $category, $permissioncategory, $permission;

	$value = $category[$key];
	$return = '';

	$op = '';
	if (checkperm('allowmanagearticle') || checkperm('allpublish') || $permission[$key]['allowpublish'] || checkperm('allowmanage') || $permission[$key]['allowmanage']) {
			$value['pushurl'] = $value['catname'];
	}

	if($level == 2) {
		$class = $last ? 'lastchildcat' : 'childcat';
		$return = '<tr class="hover"><td>&nbsp;</td><td><div class="'.$class.'">'.$value['pushurl'].'</div></td></tr>';
	} elseif($level == 1) {
		$return = '<tr class="hover"><td>&nbsp;</td><td><div class="cat">'.$value['pushurl'].'</div></td></tr>';
		$children = checkperm('allowmanagearticle') ? $category[$key]['children'] : $permissioncategory[$key]['permissionchildren'];
		$i = 1;
		$l = count($children);
		foreach((array)$children as $v) {
			$return .= showcategoryrowpush($v, 2, $i++ == $l);
		}
	} else {
		$children = checkperm('allowmanagearticle') ? $category[$key]['children'] : $permissioncategory[$key]['permissionchildren'];
		$childrennum = count($children);
		$toggle = $childrennum > 25 ? ' style="display:none"' : '';
		$return = '<tbody><tr class="hover"><td onclick="toggle_group(\'group_'.$value['catid'].'\')"><a id="a_group_'.$value['catid'].'" href="javascript:;">'.($toggle ? '[+]' : '[-]').'</a></td>'
		.'<td><div class="parentcat">'.$value['pushurl'].'</div></td></tr></tbody>
		<tbody id="group_'.$value['catid'].'"'.$toggle.'>';
		foreach((array)$children as $v) {
			$return .= showcategoryrowpush($v, 1, '');
		}
		$return .= '</tdoby>';
	}
	return $return;
}


function check_articleperm($catid,$aid=0, $isverify = false) {
	global $_G, $article;
	if($_G['group']['allowmanagearticle'] || (empty($aid) && $_G['group']['allowarticle']) || $_G['gp_modarticlekey'] == modauthkey($aid)) {
		return true;
	}
	if(!$isverify && $aid && !empty($article['uid']) && $article['uid'] == $_G['uid'] && ($article['status'] == 1 && $_G['group']['allowarticlemod'] || empty($_G['group']['allowarticlemod']))) {
		return true;
	}
	showmessage('You do not have permission to operate the current article!');
}


//对发布的tag进行检查
function posttagcheck($tagname) {
	global $_G;

	$tagname = trim($tagname);
	$tag_match = '§|№|☆|★|○|●|◎|◇|◆|□|■|△|▲|※|→|←|↑|↓|〓|＃|＆|＠|＼|︿|＿|￣|〖|〗|【|】|（|）|〔|〕|｛|｝|．|’|‘|”|“|》|《|〉|〈|〕|〔|‘|’|“|”|々|～|‖|∶|”|’|‘|｜|¨|ˇ|ˉ|·|－|…|！|？|：|；|，|、|。| | |\~|\.|\!|\@|\#|\\\$|\%|\^|\&|\*|\(|\)|\+|\=|\{|\}|\||\[|\]|\\|\:|\;|\"|\'|\<|\,|\>|\?|\/|\s';
	if(strlen($tagname) < 2 || strlen($tagname) > 15 || preg_match("/($tag_match)/", $tagname)) {
		return '';
	} else {
		require_once libfile('class/censor');
		$censor = cmsCensor::instance();
		$censor->check($tagname);

		if($censor->modbanned()) {
			return '';
		}
		if($censor->modmoderated()) {
			return '';
		}
	}
	return $tagname;
}

//处理归类输入的TAG
function posttag($tagnamestr) {
	global $_G;

	$tagarr = array('existsname'=>array(), 'nonename'=>array(), 'closename'=>array(), 'existsid'=>array());
	if(empty($tagnamestr)) return $tagarr;

	$_ttt = $tagnamearr = array();
	$valuearr = explode(',',dhtmlspecialchars($tagnamestr));

	foreach ($valuearr as $value) {
		if(count($tagnamearr) > 10) break;
		$value = posttagcheck($value);
		if($value) {
			$tagnamearr[md5(strtolower($value))] = $value;
			$_ttt[md5(strtolower($value))] = strtolower($value);
		}
	}
	if(empty($tagnamearr)) return $tagarr;

	$query = DB::query('SELECT * FROM #__common_tagslist WHERE lower(tagname) IN ('.dimplode($_ttt).')');
	while ($value = DB::fetch_array($query)) {
		$tagarr['existsid'][] = $value['tagid'];
		$tagarr['existsname'][] = $value['tagname'];
		if($value['close']) $tagarr['closename'][] = $value['tagname'];
	}

	if(!empty($tagarr['existsname'])) {
		foreach ($tagnamearr as $value) {
			if(!in_array($value, $tagarr['existsname'])) {
				$tagarr['nonename'][] = $value;
			}
		}
	} else {
		$tagarr['nonename'] = $tagnamearr;
	}

	if(!empty($tagarr['closename'])) {
		showmessage('对不起，本站不允许使用以下TAG:<p>'.implode(',', $tagarr['closename']).'</p>');
	}
	return $tagarr;
}

//获取内容中包含的TAG
function getincluetags($text, $tagtext) {
	$resultarr = array();
	$tagtext = str_replace('/', '\/', $tagtext);
	$text = clearhtml($text);
	//exit("<textarea rows=10 cols=120>$text</textarea><textarea rows=10 cols=120>$tagtext</textarea>");
	if(strlen($text)<100) return;
	if(!$tagtext||!$text) return;
	@preg_match_all("/($tagtext)/", $text, $matches);
	if(!empty($matches[1]) && is_array($matches[1])) {
		foreach ($matches[1] as $value) {
			if(strlen($value)>2) $resultarr[$value] = $value;
		}
	}
	return implode("\t", $resultarr);
}

//信息TAG关联处理
function postspacetag($op, $type, $itemid, $tagarr) {
	global $_G;
	$deletetagidarr = $addtagidarr = $spacetagidarr = array();
	if($op == 'add') {
		//如果是添加操作，那么给所有已经存在的标签的使用数据+1
		if(!empty($tagarr['existsid'])) {
			$addtagidarr = $tagarr['existsid'];
			DB::query('UPDATE #__common_tagslist SET allnum=allnum+1 WHERE tagid IN ('.dimplode($tagarr['existsid']).')');
		}
	} else {
		//如果是更新操作，那么，得检查一下本次的标签和以前的标签的差异，并根据情况进行增加、删除
		$query = DB::query('SELECT * FROM #__common_tags WHERE itemid=\''.$itemid.'\'');
		while ($spacetag = DB::fetch_array($query)) {
			if(!empty($tagarr['existsid']) && in_array($spacetag['tagid'], $tagarr['existsid'])) {
				$spacetagidarr[] = $spacetag['tagid'];
			} else {
				$deletetagidarr[] = $spacetag['tagid'];
			}
		}
		foreach ($tagarr['existsid'] as $etagid) {
			if(!empty($spacetagidarr) && in_array($etagid, $spacetagidarr)) {
			} else {
				$addtagidarr[] = $etagid;
			}
		}
		if(!empty($deletetagidarr)) {
			DB::query('DELETE FROM #__common_tags WHERE itemid='.$itemid.' AND tagid IN ('.dimplode($deletetagidarr).')');
			DB::query('UPDATE #__common_tagslist SET  allnum=allnum-1 WHERE tagid IN ('.dimplode($deletetagidarr).')');
		}
		if(!empty($addtagidarr)) {
			DB::query('UPDATE #__common_tagslist SET allnum=allnum+1 WHERE tagid IN ('.dimplode($addtagidarr).')');
		}
	}
	//TAG
	if(!empty($tagarr['nonename'])) {
		foreach ($tagarr['nonename'] as $posttagname) {
			$insertsqlarr = array(
				'tagname' => $posttagname,
				'uid' => $_G['uid'],
				'username' => $_G['username'],
				'dateline' => TIMESTAMP,
				'allnum' => 1,
			);
			$addtagidarr[] = DB::Insert('common_tagslist', $insertsqlarr, true);
		}
	}
	if(!empty($addtagidarr)) {
		$insertstr = $comma = '';
		foreach ($addtagidarr as $tagid) {
			$insertstr = '(\''.$itemid.'\',\''.$tagid.'\',\''.TIMESTAMP.'\',\''.$type.'\');';
			DB::query('REPLACE INTO #__common_tags (itemid, tagid, dateline, tagtype) VALUES '.$insertstr);
		}
	}
}
